<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace Portal\Controller;

use Common\Controller\HomebaseController;
use Portal\Model\PostsModel;

class SearchController extends HomebaseController {

    // 移动端搜索提前页
    public function mobile_search()
    {
        $hot_lists    = $this->_get_hot_search_list();
        $self_lists   = $this->_get_search_list(sp_get_current_userid());
        $this->assign('hot_lists', $hot_lists);
        $this->assign('self_lists', $self_lists);
        $this->display();
    }
    
    //搜索结果页面
    public function index() {
		$keyword        = I('request.keyword/s','');
		$list_index     = I('get.list_index', 0, 'intval');
		
		if (empty($keyword)) {
			$this -> error("关键词不能为空！请重新输入！");
		}

		// 添加搜索历史
		$user_id = sp_get_current_userid();
		$this->_add_search_list($user_id, $keyword);

		// 标签相关
        $label_ids  = M('label')->where(['name' => ['like', "%$keyword%"]])->limit(0)->select();
        $label_ids  = _array_column($label_ids, 'id');

        $is_post = true;
        if ($list_index == 0) {
            $post_type = PostsModel::POST_TYPE_ARTICLE;
        } elseif ($list_index == 1) {
            $post_type = PostsModel::POST_TYPE_NEWS;
        } elseif ($list_index == 2) {
            $is_post   = false;
        } elseif ($list_index == 3){
            $post_type = PostsModel::POST_TYPE_DISCUSSION_QUESTION;
        }

        if ($is_post) {
            // 文章 or 快讯 or 问答
            $where      = 'p.post_type = ' . $post_type . ' and ';
            $where     .= 'p.post_status = ' . PostsModel::POST_STATUS_NORMAL;
            $where     .= ' and ( p.post_title like "%' . $keyword . '%" ';

            if (!empty($label_ids)) {
                $where .= ' or ( ';
            } else {
                $where .= ')';
            }
            foreach ($label_ids as $k => $v) {
                if ($k == count($label_ids) - 1) {
                    $where .= " FIND_IN_SET( $v, p.labels) ))";
                } else {
                    $where .= " FIND_IN_SET( $v, p.labels) or ";
                }
            }

            $model = M('posts');
            $count = $model->alias('p')->where($where)->count();
            $page  = $this->page($count, 10);
            $lists = $model
                ->alias('p')
                ->join('__USERS__ u on u.id = p.post_author', 'left')
                ->where($where)
                ->field("p.*, u.user_nicename, u.user_login, (SELECT GROUP_CONCAT(name) FROM rx_label WHERE FIND_IN_SET(id, p.labels)) as label_names, (select GROUP_CONCAT(post_author_name) FROM rx_posts WHERE question_id = p.id and post_status = " . PostsModel::POST_STATUS_NORMAL . " and post_type = " . PostsModel::POST_TYPE_DISCUSSION_ANSWER . ") as answer_names")
                ->order("p.post_date desc")
                ->limit($page->firstRow, $page->listRows)
                ->select();

            foreach ($lists as $k => $q) {
                // 提问者
                if (empty($q['post_author_name'])) {
                    $q['post_author_name'] = $q['user_nicename'] ?: $q['user_login'];
                }

                // 回答者
                $answer_names = $q['answer_names'] ?: [];
                $answer_names = array_slice(explode(',', $answer_names), 0, 4);
                $q['answer_names'] = $answer_names;

                // 快讯二维码
                if ($list_index == 1) {
                    $url            = 'http://' . C('DOMAIN_NAME') . U('Portal/List/news_detail', ['id' => $q['id']]);
                    $q['qrcode']    = get_link_qrcode_path('news_detail_' . $q['id'], $url);
                }

                $lists[$k] = $q;
            }

            $this->assign("page", $page->show('default'));
            $this->assign('lists', $lists);
            $this->assign('total_pages', ceil($count / 10));

        } else {
            // 专栏作者
            $where      = 'pf.status = 1 and ';
            $where     .= 'pf.del_time = 0 and ( ';
            $where     .= 'u.user_nicename like "%' . $keyword . '%" ';

            if (!empty($label_ids)) {
                $where .= ' or ( ';
            } else {
                $where .= ')';
            }
            foreach ($label_ids as $k => $v) {
                if ($k == count($label_ids) - 1) {
                    $where .= " FIND_IN_SET( $v, pf.labels) ))";
                } else {
                    $where .= " FIND_IN_SET( $v, pf.labels) or ";
                }
            }

            $model = M('professor');
            $count = $model->alias('pf')->join('__USERS__ u on u.id = pf.user_id')->where($where)->count();
            $page  = $this->page($count, 10);
            $lists = $model
                ->alias('pf')
                ->where($where)
                ->join('__USERS__ u on u.id = pf.user_id')
                ->field("pf.id, u.user_nicename, u.user_login, u.position, u.company, u.avatar, u.signature")
                ->order("pf.created_at desc")
                ->limit($page->firstRow, $page->listRows)
                ->select();
            $this->assign("page", $page->show('default'));
            $this->assign('lists', $lists);
            $this->assign('total_pages', ceil($count / 10));
        }
        $this->assign('list_index', $list_index);
		$this->assign("keyword", $keyword);
		$this->display(":search");
    }


    // 获取用户搜索列表
    public function get_search_lists()
    {
        $re = array('status' => 1);
        $re['data']['hot_lists']    = $this->_get_hot_search_list();
        $re['data']['self_lists']   = $this->_get_search_list(sp_get_current_userid());
        $this->ajaxReturn($re);
    }

    public function _get_hot_search_list()
    {
        $hot_search_lists = M('search_history')->field("keyword, SUM(count) as total_count")->group('keyword')->order('total_count desc')->limit(10)->select();
        return $hot_search_lists;
    }

    // 添加搜索历史
    public function _add_search_list($user_id, $keyword)
    {
        $has_search = M('search_history')->where(['user_id' => $user_id, 'keyword' => $keyword])->find();
        if ($has_search) {
            M('search_history')->where(['id' => $has_search['id']])->save(['time' => time(), 'count' => $has_search['count'] + 1]);
        } else {
            $data = array(
                'user_id'   => $user_id,
                'keyword'   => $keyword,
                'time'      => time(),
                'count'     => 1,
            );
            M('search_history')->add($data);
        }
    }

    // 获取搜索历史
    public function _get_search_list($user_id)
    {
        $lists = M('search_history')->where(['user_id' => $user_id])->order('count desc, time desc')->limit(10)->select();
        return $lists;
    }
}
